<template>
	<view class="cont">
		<view class="uploadBox">
			<view style="width: 60%">
				<view @click="changImg()">
					<view v-if="!src" class="uploadItem">+</view>
					<image v-if="src" class="imgUrl" :src="src" mode="widthFix"/>
				</view>
				<view class="btn" @click="changeImg">人像动漫化</view>
			</view>
		</view>

		<view class="img_change">
			<image v-if="dmImg" class="imgUrl" :src="dmImg" mode="widthFix"/>
		</view>
	</view>
</template>

<script>
	import OCR from '../../js_sdk/effects/effects'
	export default {
		data() {
			return {
				src: '', // 上传的图片
				imgData: '', // 转换base64之后的图片
				dmImg: '' // 转换之后的动漫图片
			}
		},
		methods: {
			changImg() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original'],
					sourceType: ["camera", "album"], //拍照或相册
					success: (res) => {
						// console.log(res);
						this.src = res.tempFilePaths[0]
						res.tempFiles.forEach((item, index) => {
							this.urlTobase64(res.tempFilePaths[index], item);
						});
					}
				})
			},
			urlTobase64(url, item) {
				var itemname = item.name.split(".")[0];
				var itemtype = item.name.split(".")[1];
				var base64 = "";
				uni.request({
					url: url,
			 		method: "GET",
					responseType: "arraybuffer",
					success: (res) => {
						base64 = uni.arrayBufferToBase64(res.data); // 把arraybuffer转成base64
						var img = {
							name: itemname,
							size: item.size,
							type: itemtype,
							content: base64,
							url: url,
							new: true,
							state: -1,
						}
						this.imgData = img.content
					},
				});
			},
			async changeImg() {
				var result = await OCR.ocr({func:'imgeffects',b64:this.imgData})
				// console.log(result)
				this.dmImg = 'data:image/jpeg;base64,' + result.image
			}
		}
	}
</script>

<style lang="scss" scoped>
.cont {
	padding-top: 50rpx;
	.uploadBox {
		background-color: #FFFFFF;
		display: flex;
		justify-content: center;
		.uploadItem {
			width: 100%;
			height: 420rpx;
			background-color: #f1f7ff;
			border-radius: 15rpx;
			position: relative;
			text-align: center;
			line-height: 420rpx;
			font-size: 80rpx;
			color: #ccc;
		}
		.imgUrl {
			width: 450rpx;
			height: 420rpx;
			img {
				height: 420rpx;
			}
		}
		.btn {
			width: 100%;
			height: 75rpx;
			line-height: 75rpx;
			background-color: #007aec;
			border-radius: 12rpx;
			text-align: center;
			color: #fff;
			margin-top: 40rpx;
		}
	}
	.img_change {
		display: flex;
		justify-content: center;
		.imgUrl {
			width: 450rpx;
			height: 420rpx;
		}
	}
}
</style>
